import {
  LogoutOutlined,
  SettingOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { Avatar, Menu, Spin, Modal, message } from 'antd';
import { stringify } from 'querystring';
import { useCallback, useState, useRef } from 'react';
import HeaderDropdown from '../HeaderDropdown';
import UserForm from './UserForm';
import styles from './index.less';
import { updateUser } from '@/services/api/user';
/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
  // await outLogin();
  localStorage.removeItem('token');
  localStorage.removeItem('user');
  const { search, pathname } = history.location;
  const urlParams = new URL(window.location.href).searchParams;
  /** 此方法会跳转到 redirect 参数所在的位置 */
  const redirect = urlParams.get('redirect');
  // Note: There may be security issues, please note
  if (window.location.pathname !== '/login' && !redirect) {
    history.replace({
      pathname: '/login',
      search: stringify({
        redirect: pathname + search,
      }),
    });
  }
};

const AvatarDropdown = ({ menu }) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const actionRef = useRef();
  const userFormRef = useRef();
  const onMenuClick = useCallback(
    (event) => {
      const { key } = event;
      if (key === 'logout') {
        setInitialState((s) => ({ ...s, currentUser: undefined }));
        loginOut();
        return;
      }
      if (key === 'editpassword') {
        setIsModalOpen(true);
        return;
      }
    },
    [setInitialState],
  );

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  const { currentUser } = initialState || {};

  if (!currentUser || !currentUser.username) {
    return loading;
  }
  const handleOk = () => {
    userFormRef.current?.form?.validateFields().then((values) => {
      console.log(values, 'ddd');
      setConfirmLoading(true);
      updateUser({ ...values, id: currentUser.id }).then((res) => {
        console.log(res);

        if (res.code === 0) {
          setIsModalOpen(false);
          message.success('修改成功');
        } else {
          message.error(res.msg);
        }
        setConfirmLoading(false);
      });
    });
  };
  const menuItems = [
    {
      key: 'editpassword',
      icon: <UserOutlined />,
      label: '修改密码',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  const menuHeaderDropdown = (
    <Menu
      className={styles.menu}
      // selectedKeys={[]}
      onClick={onMenuClick}
      items={menuItems}
    />
  );
  //
  return (
    <>
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          {/* <Avatar
          className={styles.avatar}
          icon={<UserOutlined />}
          // src={currentUser.avatar}
          alt="avatar"
        /> */}
          <span className={`${styles.name} anticon`}>
            {currentUser?.username}
          </span>
        </span>
      </HeaderDropdown>
      <Modal
        title={'修改密码'}
        open={isModalOpen}
        onOk={handleOk}
        destroyOnClose
        onCancel={() => setIsModalOpen(false)}
      >
        <UserForm
          ref={userFormRef}
          data={currentUser}
          onSuccess={() => {
            setIsModalOpen(false), actionRef.current.reload();
          }}
        ></UserForm>
      </Modal>
    </>
  );
};

export default AvatarDropdown;
